import React from 'react';
import { connect } from 'react-redux';
import qs from 'querystring';
import { Icon, Layout, Pagination } from 'antd';
import { hashHistory, Link } from 'react-router';
import styles from './style.css';
import { getCategory } from '../../actions/categoryAction';
import { getArticleByCategoryId, updateSideCategory } from '../../actions/homeAction';
import Menus from './menus';
import 'rc-menu/assets/index.css';
const { Header, Content, Footer } = Layout;

@connect(state => ({
  category: state.admin.category,
  sideCategory: state.home.sideCategory,
  categoryPath: state.home.categoryPath,
  categoryArticles: state.home.categoryArticles,
}), { getCategory, getArticleByCategoryId, updateSideCategory })
export default class extends React.Component {

  unlisten = f => f;

  async componentDidMount() {
    document.title = '﻿中正（深圳）投资有限公司';

    await this.props.getCategory();
    await this.getData();
    this.unlisten = hashHistory.listen(async (loc) => {
      if (loc.action === 'POP') {
        await this.getData();
      }
    });

  }

  async getData() {
    const seprator = location.hash.indexOf('?');
    const querystring = location.hash.slice(seprator + 1);
    const { cid } = qs.parse(querystring);
    const { subMenuIds, firstLevel } = await this.props.updateSideCategory(cid);
    const res = await this.props.getArticleByCategoryId(cid, subMenuIds);

    if (res) {
      if (firstLevel && subMenuIds.length === 0) {
        const { id } = res.data.data.pop();
        this.unlisten();
        hashHistory.push(`/article?cid=${cid}&id=${id}`);
      } else if (!firstLevel && subMenuIds.length === 0 && res.data.total === 1) {
        const { id } = res.data.data.shift();
        hashHistory.push(`/article?cid=${cid}&id=${id}`);
      }
    }
  }

  componentWillUnmount() {
    this.unlisten();
  }

  render() {
    const { category, sideCategory, categoryArticles, categoryPath } = this.props;
    const { data = [], total } = categoryArticles;
    const itemRender = (current, type, originalElement) => {
      if (type === 'prev') {
        return <a>上一页</a>;
      } else if (type === 'next') {
        return <a>下一页</a>;
      }
      return originalElement;
    };
    return (
      <Layout>
        <Header style={{
          background: '#920003',
          width: '100%',
          height: '90px',
          lineHeight: '90px',
          margin: '0 auto'
        }}>
          <div className={styles.center1200}>
            <Link to={`/`} className={styles.logo}></Link>
            <Menus list={category.list} />

          </div>
        </Header>
        <Content className={styles.container}>
          <div className={styles.sideMenu}>
            {
              sideCategory.map(item =>
                <div className={styles.menuCell} key={`sidemenu-${item.id}`}>
                  <Link to={`/category?cid=${item.id}`}>
                    <div className={styles.link}>{item.name}</div>
                  </Link>
                </div>
              )
            }
          </div>
          <div style={{ flex: 1 }}>
            <div className={styles.pageHeader}>
              当前位置：
              <Link className={styles.routeLink} to={`/`}>首页</Link>
              {
                Array.isArray(categoryPath) && categoryPath[0]
                  ?
                  <span>
                    <Icon className={styles.divider} type="right" />
                    <Link className={styles.routeLink}
                          to={`/category?cid=${categoryPath[0].id}`}>{categoryPath[0].name}</Link>
                  </span>
                  : null
              }

              {
                Array.isArray(categoryPath) && categoryPath[1]
                  ?
                  <span>
                    <Icon className={styles.divider} type="right" />
                    <Link className={styles.routeLink}
                          to={`/category?cid=${categoryPath[1].id}`}>{categoryPath[1].name}</Link>
                  </span>
                  : null
              }
            </div>
            <ul className={styles.content}>
              {
                Array.isArray(data) && data.length > 0
                  ?
                  data.map(item =>
                    <li className={styles.articleList} key={`article-${item.id}`}>
                      <Link
                        className={styles.articleListLink}
                        to={`/article?cid=${item.cid}&id=${item.id}`}
                      >
                        {!(+item.top) ?
                          item.title :
                          <div><span style={{ color: '#920003', margin: '0 10px 0 0' }}>[置顶]</span>{item.title}</div>}
                      </Link>
                      <div style={{ flex: 1 }}></div>
                      <div>{item.create_time}</div>
                    </li>
                  )
                  : <p style={{ lineHeight: '50px' }}>没有数据</p>
              }
            </ul>
            {
              total > 0
                ?
                <div style={{ display: 'flex', justifyContent: 'center', margin: '30px 0 0' }}>
                  <Pagination total={total} itemRender={itemRender} />
                </div>
                : null
            }
          </div>
        </Content>
        <Footer className={styles.footer}>
          <a href="http://www.miitbeian.gov.cn/" target="_blank" className={styles.footerLink}>粤ICP备18013179号</a>
          <span style={{ color: '#999', fontSize: '12px', margin: '0 0 0 10px' }}>All Rights Reserved ©2017</span>
          <Link to="/login?type=0" style={{ margin: '0 0 0 10px', fontSize: '12px', color: '#999' }}>管理员登录</Link>
        </Footer>
      </Layout>
    );
  }
}
